package com.digitalchina.lxnsy.activity.old;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.annotation.NonNull;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.apkfuns.logutils.LogUtils;
import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.api.BusinessAccount;
import com.digitalchina.lxnsy.base.BaseActivity;
import com.digitalchina.lxnsy.constant.Constant;
import com.digitalchina.lxnsy.constant.MSG;
import com.digitalchina.lxnsy.entity.PointVO;
import com.digitalchina.lxnsy.entity.UserVO;
import com.digitalchina.lxnsy.toolkit.ActivityTaskManager;
import com.digitalchina.lxnsy.toolkit.DateStyle;
import com.digitalchina.lxnsy.toolkit.DateUtil;
import com.digitalchina.lxnsy.toolkit.FastJsonUtil;
import com.digitalchina.lxnsy.toolkit.GotoUtil;
import com.digitalchina.lxnsy.toolkit.Utils;
import com.digitalchina.lxnsy.xml.RongCloudXML;
import com.digitalchina.lxnsy.xml.UserXML;

import java.io.Serializable;
import java.util.List;
import java.util.Set;

import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;


import static com.digitalchina.lxnsy.constant.Constant.MSG_SET_ALIAS;


/**
 * ================================================
 * 项目名称：bigdata
 * 类描述：
 * 包名：com.digitalchina.bigdata.activity
 * 创建人：白彦东
 * 创建时间：2016/12/19 19:25
 * 修改备注：
 * ================================================
 */

public class LoginSelectTypeActivity extends BaseActivity {


    private UserVO userVO;

    private String userAccId;


    @Override
    public void setLayout() {
        setContentLayout(R.layout.activity_login_type_select);
        setTitle("类型选择");
    }

    @Override
    public void initMember() {

        userVO = (UserVO) getIntent().getSerializableExtra("userVO");

        userAccId = userVO.getUseraccid();
    }

    @Override
    public void addListener() {

    }

    @Override
    public void setHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                dismissDialog();
                switch (msg.what) {
                    case MSG.MSG_ATTACH_LOCAL_DATA_SUCCESS:   // 认证成功
                        callBack(msg.obj);
                        break;
                    case MSG.MSG_ATTACH_LOCAL_DATA_FIELD:
                        showToast(msg.obj.toString());
                        break;
                    case MSG_SET_ALIAS:
                        LogUtils.e("Set alias in handler.");
                        JPushInterface.setAliasAndTags(getApplicationContext(), (String) msg.obj, null, mAliasCallback);
                        break;
                    case MSG.MSG_GET_USER_RC_TOKEN_SUCCESS:
                        getTokenSuccess(msg.obj);
                        break;
                    case MSG.MSG_GET_USER_RC_TOKEN_FIELD:
                        showToast(msg.obj.toString());
                        break;
                }
            }

        };
    }

    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {

        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
                    LogUtils.e(logs);
                    break;

                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    LogUtils.e(logs);
                    if (Utils.isConnected(getApplicationContext())) {
                        mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS, alias), 1000 * 60);
                    } else {
                        LogUtils.e("No network");
                    }
                    break;

                default:
                    logs = "Failed with errorCode = " + code;
                    LogUtils.e(logs);
            }

        }

    };

    /**
     * 获取token成功 保存用户信息并跳转
     */
    private void getTokenSuccess(Object obj) {

        LogUtils.e("获取服务端Token成功,已保存到XML");

        // 解析获取到的token
        String token = FastJsonUtil.getString(obj.toString(), "data");
        RongCloudXML.setUserToken(LoginSelectTypeActivity.this, UserXML.getUserId(this), token);

    }


    @Override
    public void callBack(Object object) {

        UserVO userVO = FastJsonUtil.getBean(object.toString(), "body", "", UserVO.class);

        List<PointVO> pointVOList = FastJsonUtil.getListBean(object.toString(), "body", "rewardPointDetailList", PointVO.class);


        if (userVO == null) {
            showToast("登录失败：用户信息异常");
            return;
        }

        if (!userVO.getUserType().equals(Constant.USER_TYPE_PERSON)
                && !userVO.getUserType().equals(Constant.USER_TYPE_EXPERT)) { //除了个人用户和专家 其他无登录权限
            new MaterialDialog.Builder(this)
                    .title("提示")
                    .content("对不起，该用户没有权限！")
                    .positiveText("确定")
                    .show();
            return;
        }

        showToast("登录成功");

        //个人信息存储
        UserXML.setUserVO(this, userVO);
        setAlias(userVO.getUseraccid().replace("-", ""));

        // 注册为个人用户
        if (userVO.getUserType().equals(Constant.USER_TYPE_PERSON)) {
            // 判断融云XML里是否有该用户对应的Token
//            if (RongCloudXML.getUserToken(this, userVO.getUseraccid()).equals("default")) {
//                LogUtils.e("XML里没有该用户userID对应的Token,正在服务端获取...");
//                // 如果没有则调接口获取token
//                BusinessRongIM.getUserRCToken(this, userVO.getUseraccid(), userVO.getUserName(), mHandler);
//            } else {
//                // 如果融云为断开状态  有token则直接连接融云
//                if (RongIM.getInstance().getCurrentConnectionStatus().equals(RongIMClient.ConnectionStatusListener.ConnectionStatus.CONNECTED)) {
//                    LogUtils.e("融云IM连接状态正常");
//                } else {
//                    LogUtils.e("直接从XML获取的Token连接融云");
//                    connect(RongCloudXML.getUserToken(this, userVO.getUseraccid()));
//                }
//
//            }

            UserXML.setTodayLogin(LoginSelectTypeActivity.this, DateUtil.getCurrentDate(DateStyle.YYYY_MM_DD));
            UserXML.setLoginStatus(LoginSelectTypeActivity.this, UserXML.USER_IS_LOGIN_VALUE);





            if (ActivityTaskManager.getInstance().size() > 1) {
                Intent i = new Intent();
                Bundle bundle = new Bundle();
                bundle.putSerializable("pointVOList", (Serializable) pointVOList);
                i.putExtras(bundle);
                setResult(1, i);
                finish();
            } else {
                GotoUtil.gotoActivity(LoginSelectTypeActivity.this, MainActivity.class, true, "pointVOList", pointVOList);
            }
        } else {
            // 注册为专家用户

            GotoUtil.gotoActivity(LoginSelectTypeActivity.this, SaveExpertInfoActivity.class, true);
        }
    }

    private void setAlias(String alias) {
        LogUtils.e(alias);
        if (TextUtils.isEmpty(alias)) {
            LogUtils.e("alias is empty");
            return;
        }
        if (!Utils.isValidTagAndAlias(alias)) {
            LogUtils.e("alias is not valid");
            return;
        }

        //调用JPush API设置Alias
        mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, alias));
    }

    @Override
    public void rightOnClick() {
        GotoUtil.gotoActivity(this, RegisterTypeSelectActivity.class, true);
    }

    /**
     * 登录
     */
    private void login() {

//        String loginName = StringUtil.getEditText(loginEtUserName);
//        String loginPwd = StringUtil.getEditText(loginEtUserPwd);
//
//        if (StringUtil.isStrEmpty(loginName)) {
//            showToast("请输入用户名");
//            return;
//        }
//
//        if (StringUtil.isStrEmpty(loginPwd)) {
//            showToast("请输入密码");
//            return;
//        }

//        showDialog("登录中,请稍候...");
//        BusinessAccount.login(this, loginName, EncryptUtil.SHA1(loginPwd), mHandler);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            if (getIntent().hasExtra("logout")) {
                GotoUtil.gotoActivity(LoginSelectTypeActivity.this, MainActivity.class, true);
            } else
                finish();
            return false;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    @OnClick({R.id.login_select_layout_person, R.id.login_select_layout_expert})
    public void onViewClicked(final View view) {
        new MaterialDialog.Builder(LoginSelectTypeActivity.this)
                .title("提示")
                .content("选择后将无法变更，是否继续？")
                .positiveText("确定")
                .negativeText("取消")
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        switch (view.getId()) {
                            case R.id.login_select_layout_person:
                                BusinessAccount.attachLocalData(LoginSelectTypeActivity.this, userVO.getUsermobilephone(), Constant.USER_TYPE_PERSON, userAccId, mHandler);
                                break;
                            case R.id.login_select_layout_expert:
                                BusinessAccount.attachLocalData(LoginSelectTypeActivity.this, userVO.getUsermobilephone(), Constant.USER_TYPE_EXPERT, userAccId, mHandler);
                                break;
                        }
                    }
                })
                .show();

    }
}


